package com.joint.web.action.app;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Maps;
import com.joint.base.bean.SystemConfig;
import com.joint.base.entity.FileManage;
import com.joint.base.mp.WxMpInCacheConfigStorage;
import com.joint.base.service.UsersService;
import com.joint.core.entity.Knowledge;
import com.joint.core.service.KnowledgeService;
import com.joint.web.action.BaseAction;
import com.mongodb.gridfs.GridFSDBFile;
import com.opensymphony.xwork2.ModelDriven;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * 后台Action类 - 知识库管理
 */
@ParentPackage("app")
public class KnowledgeAction extends BaseAction implements ModelDriven<Knowledge> {

    private static final long serialVersionUID = -3957546401899874034L;

    private Knowledge knowledge;
	private List<Knowledge> knowledgeList;
    private String gridId;
    private String fileUrl;
    private String urlData;
    //文件后缀名
    private String prefix;
    //配置类型
    private String configType;

    @Resource
    private UsersService usersService;
	@Resource
	private KnowledgeService knowledgeService;
    @Resource
    private WxMpInCacheConfigStorage wxMpInCacheConfigStorage;
    @Resource
    private SystemConfig systemConfig;

	/**
	 * 知识库列表
	 * @return String
	 * @throws Exception
	 */
	public String getList() throws Exception {

        pager = new Pager();
        pager.setPageNumber(pageIndex);// 页码
        pager.setPageSize(pageSize);// 页Size
        if(StringUtils.isNotEmpty(pageProperty)&&StringUtils.isNotEmpty(pageKeyword)){
            pager.setProperty(pageProperty);
            pager.setKeyword(pageKeyword);
        }
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        Map<String, Object> map;
        map = Maps.newHashMap();
        map.put("name", pageKeyword);
        map.put("company", usersService.getCompanyByUser());
        map.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        pager = knowledgeService.findByPager(pager,map);

        knowledgeList = (List<Knowledge>) pager.getList();
        if(knowledgeList == null){
            knowledgeList = new ArrayList<Knowledge>();
        }

        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();

        for (Knowledge temp : knowledgeList) {
            Map<String, Object> tempMap = knowledgeService.getListItemMap(temp);
            dataRows.add(JSONObject.fromObject(tempMap));
        }

        data.put("pageNum", pageIndex);//页数
        data.put("pageSize", knowledgeList.size());//记录数
        data.put("pageCount", pager.getPageCount());//总页数
        data.put("totalCount", pager.getTotalCount());//总记录数
        data.put("dataRows", JSONArray.fromObject(dataRows));//数据

        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
	}

	/**
	 * 知识库详情
     *
	 * @return String
	 * @throws Exception
	 */
	public String getDetail() throws Exception {
//        LogUtil.info("keyId:"+keyId);
        if (StringUtils.isNotEmpty(keyId)) {
            knowledge = knowledgeService.get(keyId);
            if (knowledge != null) {
                Map<String, Object> data = knowledgeService.getDetailMap(knowledge);
                return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
            }
        }
        return ajaxHtmlAppResult(0, "无法找到该文档，可能已被删除！", null);
	}

	@Override
	public Knowledge getModel() {
		if(knowledge == null){
            knowledge = new Knowledge();
		}
		return knowledge;
	}

    //图文说明
    public String webview() {
//        LogUtil.info("webview keyId:"+keyId);
        if (StringUtils.isNotEmpty(keyId) == true) {
            knowledge = knowledgeService.get(keyId);
        }
        return "webview";
    }

    //在线预览
    public String fileview(){
        if(StringUtils.isEmpty(keyId)) return ajaxHtmlAppResult(0, "无法找到该文档，可能已被删除！", null);
        LogUtil.info("fileview keyId:"+keyId);
        knowledge = knowledgeService.get(keyId);

        String[] readType = new String[]{"pdf","doc","docx","xls", "xlsx"};

        String knowledgeId = knowledge.getKnowledgeId();
        if(StringUtils.isEmpty(knowledgeId)){
            urlData = "fail";   //没有上传附件
//            LogUtil.info("fileview fail:"+urlData);
            ajaxHtmlAppResult(0, "没有附件，可能已被删除！", null);
        }else{
            FileManage fm = fileManageService.get(knowledgeId);
            String gridId = fm.getGridId();
            GridFSDBFile file =gridFSGet(gridId);
            String fileName = file.getFilename();
            prefix = fileName.substring(fileName.lastIndexOf(".")+1);
            if(!Arrays.asList(readType).contains(prefix)){
                urlData = "error";  //不是符合条件的文件
//                LogUtil.info("fileview error:"+urlData);
                ajaxHtmlAppResult(0, "不是符合条件的文件，无法预览！", null);
            }else{
                configType = systemConfig.getType();
                String url = wxMpInCacheConfigStorage.getHttpHost() + "/" + systemConfig.getWebroot() + "/com/file!readDoc.action?keyId=" + knowledgeId;

                if(configType.equals("2")){
                    fileUrl = "http://api.idocv.com/view/url?url=" + url;
                }else if(configType.equals("3")){
                    fileUrl = "http://test02.9joint.com/JacobPdf/WFileToPdf?domain=" + wxMpInCacheConfigStorage.getHost() + "&gridId=" + gridId;
//                    fileUrl = "http://test02.9joint.com/JacobPdf/WFileToPdf?domain=10.10.11.49:8089&gridId=" + gridId;
                }else {
                    fileUrl = "http://officeweb365.com/o/?i="+systemConfig.getOfficeId()+"&furl="+url;
                }

                LogUtil.info("{fileUrl}"+fileUrl);

            }
        }
       return ajaxHtmlAppResult(1, fileUrl, null);
//        return "fileview";
    }

    public Knowledge getKnowledge() {
        return knowledge;
    }

    public void setKnowledge(Knowledge knowledge) {
        this.knowledge = knowledge;
    }

    public String getUrlData() {
        return urlData;
    }

    public void setUrlData(String urlData) {
        this.urlData = urlData;
    }

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public String getFileUrl() {
        return fileUrl;
    }

    public void setFileUrl(String fileUrl) {
        this.fileUrl = fileUrl;
    }
}
